﻿using Compass.Maui.Pages.FinishGoods;
using Compass.Maui.Services.FinishGoods;

namespace Compass.Maui.ViewModels.FinishGoods;

public partial class PackingListsPageViewModel:BaseViewModel
{
    private readonly IPackingListService _packingListService;
    private readonly INavigationService _navigationService;
    public PackingListsPageViewModel(IPackingListService packingListService,INavigationService navigationService)
    {
        _packingListService = packingListService;
        _navigationService = navigationService;
    }

    public ObservableRangeCollection<PackingListDto> PackingListDtos { get; } = new();


    [RelayCommand]
    private async Task GetPackingListDtosAsync()
    {
        await IsBusyFor(async () =>
        {
            if (IsRefreshing)
            {
                IsRefreshing = false;
                return;
            }
            try
            {
                PackingListDtos.ReplaceRange(await _packingListService.GetPackingListDtosAsync(0, Consts.PageSize,Search));
            }
            catch (Exception e)
            {
                await Shell.Current.DisplayAlert("Error!", $"Unable to get packinglists:{e.Message}", "OK");
            }
            finally
            {
                IsRefreshing = false;
            }
        });
    }

    [RelayCommand]
    private async Task LoadMoreAsync()
    {
        await IsBusyFor(async () =>
        {
            if (IsRefreshing)
            {
                IsRefreshing = false;
                return;
            }
            try
            {
                PackingListDtos.AddRange(await _packingListService.GetPackingListDtosAsync(PackingListDtos.Count, Consts.PageSize,Search));
            }
            catch (Exception e)
            {
                await Shell.Current.DisplayAlert("Error!", $"Unable to get packinglists:{e.Message}", "OK");
            }
            finally
            {
                IsRefreshing=false;
            }
        });
    }


    [RelayCommand]
    private async Task GoToWeighingAsync(PackingListDto? packingListDto)
    {
        if ( packingListDto is not { HavePackingList: true }) return;
        
        await IsBusyFor(async () =>
        {
            await _navigationService.NavigateToAsync(nameof(WeighingPage),
                new Dictionary<string, object?>()
                {
                    {nameof(PackingListDto),packingListDto}
                });
        });
    }

    #region 筛选
    private string search;
    /// <summary>
    /// 搜索条件属性
    /// </summary>
    public string Search
    {
        get => search;
        set
        {
            search = value;
            OnPropertyChanged();
            Filter();
        }
    }
    private async void Filter()
    {
        await GetPackingListDtosAsync();
    } 
    #endregion
}